package com.xhs.filter;

import com.alibaba.fastjson.JSON;
import com.xhs.config.RedisKeyConfig;
import com.xhs.config.SystemConfig;
import com.xhs.entity.User;
import com.xhs.utils.JedisUtils;
import org.springframework.context.annotation.ComponentScan;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

//实现过滤器 实现令牌的续期
@WebFilter("/*")
@ComponentScan
public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.获取请求的令牌
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        String token=request.getHeader(SystemConfig.HEADER_TOKEN);
        //2.校验令牌的是否存在
        String key= RedisKeyConfig.LOGIN_TOKEN+token;
        if(JedisUtils.checkKey(key)){
            //3.自动续期-30
            String phone= JSON.parseObject(JedisUtils.getStr(key), User.class).getPhone();
            JedisUtils.expire(RedisKeyConfig.LOGIN_PHONE+phone,RedisKeyConfig.LOGIN_TOKEN_TIME);
            JedisUtils.expire(key,RedisKeyConfig.LOGIN_TOKEN_TIME);
        }
        //4.放行
        filterChain.doFilter(request,servletResponse);
    }

    @Override
    public void destroy() {
    }
}
